import { createRouter, createWebHashHistory } from 'vue-router'
import routes from './routes'
import NProgress from '@/utils/nprogress'
import { changeTitle } from '@/utils/title'
import { useUserStore } from '@/store/user'
import { useKeepAliveStore } from '@/store/keepAlive'

const router = createRouter({
    history: createWebHashHistory(),
    routes // `routes: routes` 的缩写
})

// 未授权时可访问的白名单
const whiteList = ['/login']

// 路由跳转前的监听操作
router.beforeEach((to, _from, next) => {
    const store = useUserStore()
    NProgress.start()
    if (store.token) {
        to.meta.title ? changeTitle(to.meta.title) : '' // 动态title
        if (to.path === '/login') {
            next('/')
            return
        }
        next()
    } else if (whiteList.includes(to.path)) {
        to.meta.title ? changeTitle(to.meta.title) : '' // 动态title
        next()
    } else {
        next('/login') // 全部重定向到登录页
        to.meta.title ? changeTitle(to.meta.title) : '' // 动态title
    }
})

// 路由跳转后的监听操作
router.afterEach((to, _from) => {
    const keepAliveStore = useKeepAliveStore()
    const keepAliveComponentsName = keepAliveStore.keepAliveComponentsName || []
    const name = to.matched[to.matched.length - 1].components.default.name
    // console.log('name', to.matched)
    // console.log('keepAliveComponentsName', to.meta && to.meta.cache, name, !keepAliveComponentsName.includes(name))
    if (to.meta && to.meta.cache && name && !keepAliveComponentsName.includes(name)) {
        keepAliveStore.keepAliveComponentsName.push(name)
    }
    NProgress.done()
})

export default router
